package com.jfree.nettyshow.common;

import com.alibaba.fastjson.JSON;
import com.jfree.nettyshow.entity.Session;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


public class SessionManager {

    private static Logger logger = LoggerFactory.getLogger(SessionManager.class);
    private ConcurrentHashMap<String, Session> onLine;
    private AttributeKey<Session> attributeKey = AttributeKey.valueOf(CommonConstant.SESSION_CHANNEL_KEY);
    private Set<String> addressSet = new HashSet<>();

    public SessionManager(ConcurrentHashMap<String, Session> onLine) {
        this.onLine = onLine;
    }

    public boolean put(String key, Session session) {
        return onLine.put(key, session) != null;
    }

    public void remove(String key) {
        logger.info("sessionManager删除key：" + key + " 的channel");
        onLine.remove(key);
    }

    public void closeChannel(Channel channel) {
        if (channel == null) {
            return;
        }
        if (channel.isActive()) {
            channel.close();
            remove(channel.id().asShortText());
            channel.attr(attributeKey).set(null);
            clearSession(channel.attr(attributeKey).get());
        }

    }

    /**
     * 给所有人发送消息
     *
     * @param result
     */
    public void massSend(Result result) {
        if (result != null) {
            String res = JSON.toJSONString(result);
            onLine.forEach((k, v) -> {
                if (v.getChannel().isActive()) {
                    v.getChannel().writeAndFlush(res);
                }
            });
        }
    }

    public Session getSession(Channel channel) {
        return onLine.get(channel.id().asShortText());
    }

    public Session getSession(String id) {
        return onLine.get(id);
    }

    public void clearSession(Session session) {
        if (session == null) {
            return;
        }
        session.setLastAccessTime(null);
        session.setSessionId(null);
        session.setChannel(null);
        session.setCheck(false);
    }

    public boolean contains(String address) {
        synchronized (addressSet) {
            if (addressSet.contains(address)) {
                return false;
            } else {
                return true;
            }
        }
    }
}
